<?php
namespace hotel\modules\apiadmin\controllers;

use hotel\common\models\App;
use Yii;
use yii\rest\ActiveController;
use yii\web\Response;
use hotel\common\models\DB;


/**
 * 接口基础处理
 * @author Administrator
 * @param  所有版本接口的控制器父类
 */
class CoreController extends ActiveController
{
    public  $modelClass = '';
    private $http_id;
    public  $post;
    public  $get;
    public  $_user;  //用户信息
    public  $_uid;
    public  $request;
    public  $db;
    public  $appid;
    public  $shop_type;
    protected $allowAllAction = [
        'apiadmin/app/app-list',
        'apiadmin/app/app-edit',
        'apiadmin/app/get-app-data-by-id',
        'apiadmin/app/get-xop-config-by-appid',
        'apiadmin/app/edit-xop-config',
        'apiadmin/hotel/download-image',
		'apiadmin/comment/list',
		'apiadmin/comment/change',
		'apiadmin/comment/del',


    ];
    protected $userInfo;//登录信息
    protected $permissions;//角色权限信息
    protected $permissionApps;//角色权限信息



    public function beforeAction($action)
    {
        $auth_module = $this->module->id;
        $auth_controller = $this->id;
        $auth_action = $this->action->id;
        $router = $auth_module . '=' . $auth_controller . '=' . $auth_action;

        $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
        header('Access-Control-Allow-Origin:'.$origin);
        header("Access-Control-Request-Headers: Origin, X-Requested-With, Content-Type, Accept,Authorization");
        header('Access-Control-Allow-Headers:Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization');
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS');
        header('Access-Control-Allow-Credentials:true');

        //获取请求方式，筛选OPTIONS请求，返回204状态码，告诉客户端预检通过
        $method = Yii::$app->request->method;
        if($method == 'OPTIONS'){
            header("HTTP/1.1 204 OK");die;
        }


        /*请求认证中心,获取用户登录信息*/
        if(isset(Yii::$app->session->get('loginInfo')->userInfo)){
            $this->userInfo = Yii::$app->session->get('loginInfo')->userInfo;
            $this->permissions = Yii::$app->session->get('loginInfo')->permissions;
            $this->permissionApps = Yii::$app->session->get('loginInfo')->permissionApps;
        };
        if (in_array($action->getUniqueId(), $this->allowAllAction)) {
            return true;
        }
        //判断是否登录
        if(!empty($this->userInfo)){
            $header_data = Yii::$app->getRequest()->getHeaders();
            $this->appid = $header_data['Authorization'];
            if(empty($this->appid)){
                Yii::$app->response->format = Response::FORMAT_JSON;
                Yii::$app->response->data = [
                    'code' => 400,
                    'msg'  => 'appid不能为空',
                ];
                return false;
            }
            $app_data = App::find()->where("appid = '$this->appid'")->asArray()->one();
            if(empty($app_data)){
                Yii::$app->response->format = Response::FORMAT_JSON;
                Yii::$app->response->data = [
                    'code' => 400,
                    'msg'  => 'appid有误',
                ];
                return false;
            }
            /*验证权限*/
            $pass = false;
            if($this->userInfo['issuper'] == 1 or in_array($router, Yii::$app->params['allowRouter'])){//菜单列表
                $pass = true;
            }else{
                foreach($this->permissions as $k => $v){
                    if(isset($this->get['appid'])){
                        if($v['appid'] == $this->get['appid'] and $v['m'] == $auth_module and $v['c'] == $auth_controller and $v['a'] == $auth_action){
                            $pass = true;
                            break;
                        }
                    }else{
                        if($v['m'] == $auth_module and $v['c'] == $auth_controller and $v['a'] == $auth_action){
                            $pass = true;
                            break;
                        }
                    }
                }
            }
            if(!$pass){
                Yii::$app->response->format = Response::FORMAT_JSON;
                Yii::$app->response->data = [
                    'code' => 10020,
                    'msg'  => '没有权限',
                ];
                return false;
            }


            return true;
        }else{
            Yii::$app->response->format = Response::FORMAT_JSON;
            Yii::$app->response->data = [
                'code' => 100700,
                'msg'  => '请登录',
            ];
            return false;
        }

    }

    public function request($key,$default='')
    {
        $request = array_merge(Yii::$app->request->post(),Yii::$app->request->get(),$_FILES);
        return isset($request[$key])?$request[$key]:$default;
    }


    public function out($msg='', $res = [],$extend=[]){
        $data = [
            'status' => "200"  ,
            'code'   => '0',
            'msg'    => (string)$msg,
            'data'   => $res,
        ];
        if($extend) $data['extend'] = $extend;
        return $this->send($data);
    }

    public function error($msg='', $status = '200',$code='1'){
        $data = [
            'status'=> $status."",
            'code'  => $code,
            'msg'   => (string)$msg,
        ];
        return  $this->send($data);
    }

    public function send($data=[])
    {
        $out = json_encode($data,JSON_UNESCAPED_UNICODE);
        DB::update('http_log', [ 'http_status' => $data['status'], 'response' => $out,'finish_at'=>date("Y-m-d H:i:s") ], ['id'=>$this->http_id]);
        exit($out);
    }


    protected function parameter($request = [], $model = [])
    {
        $request['create_time'] = time(); // '创建时间',  
        foreach ($request as $k => $v) {
            if (array_key_exists($k, $model->attributes))
                $model->$k = $v;
        }

        return $model;
    }


    public function model($model,$params,$scenario='',$id='')
    {

        $classDir  = 'apiadmin\\modules\\models'.'\\'.$model;
        $m = new $classDir();
        if(!$m){
            $classDir = '\\common\\models\\'.$model;
            $m = new $classDir();
        }
        if($id) $m = $m::findOne($id);

        if(!$m) $this->error(' model cannot be blank.');
        if($scenario) $m->scenario = $scenario;

        $m = $this->parameter($params,$m);
        $m->validate() ?:$this->error($this->model_errors($m->errors));
        return $m;
    }

    public function model_errors($errors=[]){
        foreach ($errors as $k=>$v){
            return $v[0];
        }
        return 'model_errors';
    }


    public function get_curl($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }


    public function post_curl($url,$params)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        // curl_setopt( $ch, CURLOPT_USERAGENT , 'xinykj.com' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt( $ch , CURLOPT_POST , 1 );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $url );
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }

    //记入日志
    public function write_log($content,$tempDir='')
    {
        if(is_array($content) || is_object($content))
            $content = json_encode($content,JSON_UNESCAPED_UNICODE);

        $content = "[".date('Y-m-d H:i:s')."]".$content."\r\n";
        $dir = rtrim(str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']),'/').'/data/logs';
        if($tempDir) $dir .= '/'.$tempDir;
        if(!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        $path = $dir.'/'.date('Y-m-d').'.txt';
        file_put_contents($path,$content,FILE_APPEND);
    }


}

?>